#include "stdafx.h"
#include "charset/byteorder.hpp"

#if defined(_MSC_VER)
#include <stdlib.h>
#endif


namespace JHCPP
{
	namespace charset
	{	
		UInt16 CByteOrder::flipBytes(UInt16 value)
		{
		#if defined(JH_HAVE_MSC_BYTESWAP)
			return _byteswap_ushort(value);
		#else
			return ((value >> 8) & 0x00FF) | ((value << 8) & 0xFF00);
		#endif
		}

		Int16 CByteOrder::flipBytes(Int16 value)
		{
			return Int16(flipBytes(UInt16(value)));
		}

		UInt32 CByteOrder::flipBytes(UInt32 value)
		{
		#if defined(JH_HAVE_MSC_BYTESWAP)
			return _byteswap_ulong(value);
		#elif defined(JH_HAVE_GCC_BYTESWAP)
			return __builtin_bswap32(value);
		#else
			return ((value >> 24) & 0x000000FF) | ((value >> 8) & 0x0000FF00)
				| ((value << 8) & 0x00FF0000) | ((value << 24) & 0xFF000000);
		#endif
		}

		Int32 CByteOrder::flipBytes(Int32 value)
		{
			return Int32(flipBytes(UInt32(value)));
		}

		UInt64 CByteOrder::flipBytes(UInt64 value)
		{
		#if defined(JH_HAVE_MSC_BYTESWAP)
			return _byteswap_uint64(value);
		#elif defined(JH_HAVE_GCC_BYTESWAP)
			return __builtin_bswap64(value);
		#else
			UInt32 hi = UInt32(value >> 32);
			UInt32 lo = UInt32(value & 0xFFFFFFFF);
			return UInt64(flipBytes(hi)) | (UInt64(flipBytes(lo)) << 32);
		#endif
		}

		Int64 CByteOrder::flipBytes(Int64 value)
		{
			return Int64(flipBytes(UInt64(value)));
		}
	}//end of namespace charset
}//end of namespace JHCPP
